package com.jcl.cloud.services.login.service;


import java.util.concurrent.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service
public class ThreadPoolService {
    private static final Logger log = LoggerFactory.getLogger(ThreadPoolService.class);

    private ExecutorService executorService;


    @PostConstruct
    public void init(){
        this.executorService = getExecutor(10);
    }


    public void execute(Runnable command){
        this.executorService.execute(command);

    }


    public static ExecutorService getExecutor() {
        return Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
    }

    public static ExecutorService getExecutor(int taskSize) {
        int size = Math.min(taskSize, Runtime.getRuntime().availableProcessors() * 2);
        return size <= 1 ? null : Executors.newFixedThreadPool(size);
    }

    public static void waitAndShutDown(ExecutorService executor) {
        if (executor != null) {
            try {
                executor.shutdown();
                executor.awaitTermination(2147483647L, TimeUnit.DAYS);
            } catch (Exception e) {
                log.error("线程池未能成功关闭", e);
            }

        }
    }
}
